<?php

namespace app\api\controller;

use app\api\model\Banner;
use app\api\model\Trends;
use app\common\controller\Api;
use think\helper\Time;
use think\Cache;
use think\Controller;
use think\Request;
use app\common\library\Token;

/**
 * 动态
 */
class Trend extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 列表
     */
    public function index(Request $request)
    {
        $length = $request->get('length');
        $trends = Trends::getTrends($length);
        $trends->items() ? $this->success('请求成功', ['trends' => $trends->items()]) : $this->error('没有数据');
    }

    /**
     * 详情
     */
    public function read($id)
    {
        $trend = Trends::find($id);
        if (!$trend) {
            $this->error('没有数据');
        }
        //记录阅读数，一个用户每天只记录一次
        $token = $this->request->header('token');
        if ($token) {
            $data = Token::get($token);
            if ($data) {
                $user_id = intval($data['user_id']);
                $reading = Cache::get('reading_'.$user_id);
                if (!$reading) {
                    list($startTime, $endTime) = Time::today();
                    $trend->reading += 1;
                    $result  = $trend->save();
                    if ($result) {
                        //标识当天已阅读过
                        Cache::set('reading_'.$user_id, $user_id, $endTime - time());
                    }
                }
            }
        }

        $this->success('请求成功', ['trend' => $trend]);
    }

    /**
     * 轮播图
     */
    public function banner()
    {
        $banners = Banner::getBanners();
        $banners ? $this->success("请求成功", compact('banners')) : $this->error("没有数据");
    }
}
